<template>
  <el-card>
    <el-button
      :icon="Plus"
      type="primary"
      :disabled="!categoryStore.category3Id"
      >添加属性</el-button
    >
    <el-table border :data="attrList" width="100%">
      <el-table-column type="index" label="序号" width="70" />
      <el-table-column prop="attrName" label="属性名称" width="180" />
      <el-table-column label="属性值列表">
        <template #default="{ row }">
          <el-tag
            class="ml-2"
            type="success"
            v-for="item in row.attrValueList"
            :key="item.id"
            >{{ item.valueName }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-tooltip content="修改属性" placement="top" effect="light">
            <el-button
              type="warning"
              size="small"
              :icon="Edit"
              @click="editAttr(row)"
            />
          </el-tooltip>
          <el-tooltip content="删除属性" placement="top" effect="light">
            <el-button
              type="danger"
              size="small"
              :icon="Delete"
              @click="removeAttr(row.id)"
            />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script lang="ts">
export default {
  name: "AttrList",
}
</script>

<script lang="ts" setup>
import { Plus, Edit, Delete } from "@element-plus/icons-vue"
import {ElMessage} from 'element-plus'
import { ref, watch, defineEmits } from "vue"
import { useCategoryStore } from "@/stores/categorySelector"
import { getCategoryListApi, removeAttrApi } from "@/api/product/attr"
import type {
  categoryListResponse,
  attrItem,
} from "@/api/product/model/attrModel"
const categoryStore = useCategoryStore()
const attrList = ref<categoryListResponse>([])
const emit = defineEmits(["setIsShowAttrList", "setAttr"])
watch(
  categoryStore,
  async (newVal) => {
    if (newVal.category3Id) {
      const { category1Id, category2Id, category3Id } = newVal
      attrList.value = await getCategoryListApi(
        category1Id as number,
        category2Id as number,
        category3Id
      )
      return
    }
    // 如果没有值，清空数据
    attrList.value = []
  },
  { immediate: true }
)
// 编辑属性
const editAttr = (row: attrItem) => {
  emit("setIsShowAttrList", false)
  emit("setAttr", row)
}
// 删除属性
const removeAttr = async(id: number) => {
  await removeAttrApi(id)
  ElMessage.success("删除属性成功");
  const { category1Id,category2Id,category3Id} = categoryStore
  attrList.value = await getCategoryListApi(category1Id as number,category2Id as number,category3Id as number);
}
</script>

<style scoped></style>
